package com.ebt.m.policy;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.data.event.EPageOperate;
import com.ebt.m.policy.adapter.AdapterPager;
import com.ebt.m.policy.bean.EventFinishAct;
import com.ebt.m.policy.bean.EventPrams;
import com.ebt.m.policy.view.FilterListView;
import com.ebt.m.widget.BaseActivity;
import com.ebt.m.widget.SlidingTabLayout;
import com.jakewharton.rxbinding2.view.RxView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Damon.Han on 2018/4/10 0010.
 *
 * @author Damon
 */
public class ActChoosePolicy extends BaseActivity {
    @BindView(R.id.btn_cancel)
    FrameLayout btnCancel;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_to_search)
    ImageView btnToSearch;
    @BindView(R.id.sliding_tab_layout)
    SlidingTabLayout slidingTabLayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.to_filter)
    CheckBox toFilter;
    @BindView(R.id.filter_container)
    LinearLayout filterContainer;
    @BindView(R.id.list_container)
    FrameLayout listContainer;
    @BindView(R.id.dialog_footer_negative)
    Button btnNegative;
    @BindView(R.id.dialog_footer_positive)
    Button btnPositive;

    private int currentPage;
    private HashMap<String, String> mapParams = new HashMap<>();
    FrgChooseByBrand frgChooseByBrand;
    FrgChooseByProducts frgChooseByProducts;
    FrgChooseByProposals frgChooseByProposals;
    FilterListView filterListView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_choose_policy);
        ButterKnife.bind(this);
        initViews();
    }

    @Override
    public void initViews() {
        super.initViews();
        AdapterPager mAdapter = new AdapterPager(
                ((FragmentActivity) getContext()).getSupportFragmentManager(),
                getTitles(),
                getFragments()
        );
        viewPager.setAdapter(mAdapter);
        slidingTabLayout.setDistributeEvenly(true);
        slidingTabLayout.setViewPager(viewPager);
        viewPager.setOffscreenPageLimit(3);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPage = position;
                refreshCurrentPage(currentPage);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        RxView.clicks(btnNegative)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    pressReset();
                });
        RxView.clicks(btnPositive)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    pressOk();
                });
        toFilter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleFilter();
            }
        });
    }

    private void toggleFilter() {
        if (filterContainer.getVisibility() == View.VISIBLE) {
            filterContainer.setVisibility(View.GONE);
            if (mapParams.size() > 0) {
                toFilter.setChecked(true);
            } else {
                toFilter.setChecked(false);
            }
        } else {
            filterContainer.setVisibility(View.VISIBLE);
            toFilter.setChecked(true);
            if (filterListView == null) {
                filterListView = new FilterListView(getContext());
                filterListView.update();
                listContainer.addView(filterListView);
            }
        }
    }

    private void pressReset() {
        filterListView.reset();
    }

    private void pressOk() {
        filterListView.pressOk();
    }

    private void refreshCurrentPage(int currentPage) {
        switch (currentPage) {
            case 0:
                frgChooseByBrand.getDataFromServer(mapParams);
                break;
            case 1:
                frgChooseByProducts.getDataFromServer(mapParams);
                break;
            case 2:
                frgChooseByProposals.getDataFromServer(mapParams);
                break;
        }
    }

    private ArrayList<String> getTitles() {
        ArrayList<String> titles = new ArrayList<String>();
        titles.add("品牌");
        titles.add("产品");
        titles.add("计划书");
        return titles;
    }

    private ArrayList<Fragment> getFragments() {
        ArrayList<Fragment> fragments = new ArrayList<>();
        //品牌
        frgChooseByBrand = FrgChooseByBrand.newInstance();
        frgChooseByProducts = FrgChooseByProducts.newInstance("");
        frgChooseByProposals = FrgChooseByProposals.newInstance("");
        fragments.add(frgChooseByBrand);
        //产品
        fragments.add(frgChooseByProducts);
        //计划书
        fragments.add(frgChooseByProposals);
        return fragments;
    }

    @OnClick({R.id.btn_cancel, R.id.btn_to_search, R.id.to_filter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel:
                finish();
                break;
            case R.id.btn_to_search:
                gotoActivity(ActSearch.class);
                break;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (inRangeOfView(toFilter, ev)) {
            return super.dispatchTouchEvent(ev);
        }
        if (filterContainer.getVisibility() == View.VISIBLE && ev.getAction() == MotionEvent.ACTION_DOWN && !inRangeOfView(filterContainer, ev)) {
            filterContainer.setVisibility(View.GONE);
        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean inRangeOfView(View view, MotionEvent ev) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int x = location[0];
        int y = location[1];
        if (ev.getX() < x || ev.getX() > (x + view.getWidth()) || ev.getY() < y || ev.getY() > (y + view.getHeight())) {
            return false;
        }
        return true;
    }


    /**
     * @return void
     * @Description: 订阅参数传递
     * @throw
     */
    @Subscribe
    public void onEvent(EventPrams params) {
        if (params == null) {
            return;
        }
        mapParams.clear();
        Map<String, String> map = params.map;
        if (map != null) {
            for (String key : map.keySet()) {
                mapParams.put(key, map.get(key));
            }
        }
        refreshCurrentPage(currentPage);
        toggleFilter();
    }

    @Override
    public void onDestroy() {
        EPageOperate operate = new EPageOperate();
        operate.from = ActChoosePolicy.class.getName();
        EventBus.getDefault().post(operate);
        super.onDestroy();
    }

    @Subscribe
    public void onEvent(EventFinishAct event) {
        finish();
    }

    @Override
    public void onBackPressed() {
        if (filterContainer.getVisibility() == View.VISIBLE) {
            toggleFilter();
        } else {
            super.onBackPressed();
        }
    }

    //退出此activity的flag
    public static final String TAG_EXIT = "exit";

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            boolean isExit = intent.getBooleanExtra(TAG_EXIT, false);
            if (isExit) {
                this.finish();
            }
        }
    }
}
